package com.danco.sn.model.dao;

import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.danco.sn.apientities.FriendshipStatus;
import com.danco.sn.apientities.IUser;
import com.danco.sn.model.hibernateutil.HibernateUtil;

public class DBManager {
	private static DBManager DBMANAGER;
	private HibernateUtil hibernateUtil = HibernateUtil.getInstance();
	private UserDAO userDao;
	private FriendDAO friendDao;
	private Logger log = Logger.getLogger(DBManager.class);

	private DBManager() {
		userDao = new UserDAO();
		friendDao = new FriendDAO();
	}

	private Session getSession() {
		return hibernateUtil.getSessionFactory().getCurrentSession();

	}

	private Transaction getTransaction(Session session) {
		return session.beginTransaction();
	}

	private void exceptionActivity(Exception e, Transaction transaction) {
		log.error(e);
		transaction.rollback();
	}

	public static DBManager getInstance() {
		if (DBMANAGER == null) {
			DBMANAGER = new DBManager();
		}
		return DBMANAGER;
	}

	public IUser autorization(String login) {
		Session session = getSession();
		Transaction transaction = getTransaction(session);
		try {
			IUser user = (IUser) userDao.read("login", login, session);
			transaction.commit();
			return user;
		} catch (HibernateException hibEx) {
			exceptionActivity(hibEx, transaction);
			return null;
		}
	}

	public Boolean registration(IUser user) {
		Session session = getSession();
		Transaction transaction = getTransaction(session);
		try {
			userDao.create(user, session);
			transaction.commit();
			return true;
		} catch (HibernateException hibEx) {
			exceptionActivity(hibEx, transaction);
			return false;
		}
	}

	public Boolean editUsersInformation(IUser user){
		Session session = getSession();
		Transaction transaction = getTransaction(session);
		try{
			userDao.update(user, session);
			transaction.commit();
			return true;
		}catch(HibernateException hibEx){
			exceptionActivity(hibEx, transaction);
			return false;
		}
	}
	
	
//_________________________Log in, registration, edit page________ 
	
	public List<IUser> getFriendList(IUser user){
		Session session = getSession();
		Transaction transaction = getTransaction(session);
		try{
			return friendDao.getListFriend(session, user, FriendshipStatus.APPROVE);
		}catch(HibernateException hibEx){
			exceptionActivity(hibEx, transaction);
			return null;
		}
	}
	
	public List<IUser> getWaitingFriend(IUser user){
		Session session = getSession();
		Transaction transaction = getTransaction(session);
		try{
			return friendDao.getListFriend(session, user, FriendshipStatus.WAITING);
		}catch(HibernateException hibEx){
			exceptionActivity(hibEx,transaction);
			return null;
		}
	}
	
}
